from datetime import datetime, timedelta
from typing import Optional , Dict
from jose import JWTError, jwt
from passlib.context import CryptContext


# 内存存储结构：{username: current_valid_token}
active_tokens: Dict[str, str] = {}
# 配置参数
SECRET_KEY = "hello-football-world"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def verify_password(plain_password: str, hashed_password: str):
    return pwd_context.verify(plain_password, hashed_password)


def create_access_token(username: str) -> str:
    # 生成新 Token 前，使旧 Token 失效（直接覆盖）
    global active_tokens

    # 生成 Token
    expire = datetime.utcnow() + timedelta(minutes=30)
    payload = {
        "sub": username,
        "exp": expire
    }
    new_token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

    # 存储到内存
    active_tokens[username] = new_token
    return new_token


from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


async def validate_token(token: str = Depends(oauth2_scheme)) -> dict:
    # 基本 JWT 验证
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if not username:
            raise HTTPException(status_code=401, detail="无效 Token")
    except jwt.JWTError:
        raise HTTPException(status_code=401, detail="Token 验证失败")
    print(username)
    # 检查是否为最新 Token
    current_valid_token = active_tokens.get(username)
    if current_valid_token != token:
        raise HTTPException(status_code=401, detail="Token 已失效")

    return payload



def revoke_old_tokens(username: str ):
    if username in active_tokens:
        del active_tokens[username]

if __name__ == "__main__":
    print(create_access_token('pcj'))
